<script>
export default {
  data() {
    return {
      form: {},
      rules: {
        password: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {len: 6, message: '验证码长度为 6 个字符', trigger: 'blur'}
        ],
      },

    }
  },
  methods: {
    updatePassword() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {  // 表单校验合法
          if (this.form.password !== this.form.confirmPassword) {
            this.$message.error("两次输入密码不一致")
          } else if (this.form.password===this.form.oldPassword || this.form.confirmPassword===this.form.oldPassword){
            this.$message.error("新密码与原始密码相同")
          }else {
            const requestData = {
              id: JSON.parse(localStorage.getItem("user")).id,
              password: this.form.password,
              oldPassword:this.form.oldPassword
            };
            this.request.post('/user/updatePassword',JSON.stringify(requestData))
                .then(res => {
                  console.log(res)
                  if(res.code===400){
                    this.$message.error(res.message)
                  }else {
                    this.$message.success("修改成功")
                    localStorage.removeItem("user")
                    this.$router.push("/login")
                  }
                })
          }

        }
      });


    }
  }

}
</script>

<template>
  <div style="display: flex; justify-content: center; align-items: center; height: 80vh;">
    <el-card style="width: 45%;">
      <el-form :model="form" label-width="100px" :rules="rules" ref="userForm">
        <el-form-item style="display: none;">
          <el-input v-model="form.id" type="hidden"></el-input>
        </el-form-item>


        <el-form-item label="原密码" prop="password">
          <el-input v-model="form.password" show-password autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" show-password autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" style="margin-left: 150px" @click="updatePassword">提交</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<style scoped>

</style>